import store from '@/store'

const MessageType = {
  TEXT: 1, // 文字消息
  VOICE: 2, // 语音消息
  CALL_INVITE_VOICE: 3, // 语音通话邀请
  CALL_INVITE_VIDEO: 4 // 视频通话邀请
}

const ConversationType = {
  NONE: 0, // 无类型
  PRIVATE: 1, // 单聊
  GROUP: 2, // 群聊
  CHATROOM: 3, // 聊天室会话
  SYSTEM: 4, // 系统消息
  ULTRA_GROUP: 5 // 超级群
}

const IMEventType = {
  SYSTEM: {
    connecting: 'connecting',
    connected: 'connected',
    disconnected: 'disconnected'
  },
  MESSAGE: {
    onMessageReceived: 'onMessageReceived'
  },
  CALL: {
    callSuccess: 'callSuccess',
    callFail: 'callFail',
    acceptSuccess: 'acceptSuccess',
    acceptFail: 'acceptFail',
    hungupSuccess: 'hungupSuccess',
    hungupFail: 'hungupFail',
    onSession: 'onSession',
    onRinging: 'onRinging',
    onAccept: 'onAccept',
    onHungup: 'onHungup',
    onTrackReady: 'onTrackReady',
    onSessionClose: 'onSessionClose'
  }
}

class UserInfo {
  constructor(userId) {
    const { users = [] } = store.state.im

    if (users.length === 0) {
      return
    }

    const { name, phone, miniOpenid, relationshipType } = users.find((u) => u.userId === userId)

    this.userId = userId
    this.name = name
    this.phone = phone
    this.miniOpenid = miniOpenid
    this.relationshipType = relationshipType
    this.avatar = ''
    this.avatarBgc = this.getRandomColor(userId)
  }

  getRandomColor(key) {
    const colors = ['#51C3FF', '#F8AC23', '#752DFD', '#01CE77', '#0076FF']
    const num = key.replace('parentUser:', '').replace('student:', '')

    if (Number(num) === NaN) return colors[0]

    const seededRandom = (number, max, min) => {
      let seed = number
      max = max || 1
      min = min || 0
      seed = (seed * 9301 + 49297) % 233280
      var rnd = seed / 233280.0
      return min + rnd * (max - min)
    }

    const min = 0
    const max = colors.length - 1
    const index = Math.round(seededRandom(num, max, min))

    if (index >= min && index <= max) {
      return colors[index]
    } else {
      return colors[0]
    }
  }
}

class Message_Base {
  constructor(_message) {
    const {
      messageId,
      messageUId,
      messageType,
      conversationType,
      senderUserId,
      targetId,
      sentTime
    } = _message

    Object.defineProperty(this, '__message__', {
      value: _message,
      enumerable: false,
      writable: false,
      configurable: false
    })

    const { userId = '' } = store.state.im

    this.messageId = messageId
    this.messageUId = messageUId
    this.messageType = this.getMessageType(messageType)
    this.conversationType = conversationType
    this.senderUserId = senderUserId
    this.receiverUserId = userId
    this.targetId = targetId
    this.sentTime = sentTime
    this.userInfo = new UserInfo(senderUserId)
  }

  getMessageType(type) {
    if (['RC:TxtMsg', 2].includes(type)) {
      return MessageType.TEXT
    } else if (['RC:HQVCMsg', 3].includes(type)) {
      return MessageType.VOICE
    } else if (['Call:InviteVoice'].includes(type)) {
      return MessageType.CALL_INVITE_VOICE
    } else if (['Call:InviteVideo'].includes(type)) {
      return MessageType.CALL_INVITE_VIDEO
    }
  }

  isTextMessage(type) {
    return ['RC:TxtMsg', 2].includes(type) ? true : false
  }

  isVoiceMessage(type) {
    return ['RC:HQVCMsg', 3].includes(type) ? true : false
  }

  isCallInviteVoiceMessage(type) {
    return ['Call:InviteVoice'].includes(type) ? true : false
  }

  isCallInviteVideoMessage(type) {
    return ['Call:InviteVideo'].includes(type) ? true : false
  }
}

class Conversation_Base {
  constructor(_conversation) {
    const { conversationType, targetId } = _conversation
    this.conversationType = this.getConversationType(conversationType)
    this.targetId = targetId
  }

  getConversationType(type) {
    switch (type) {
      case 1:
        return ConversationType.PRIVATE
      default:
        return ConversationType.NONE
    }
  }
}

class Contact {
  constructor(conversation) {
    const { targetId, unreadMessageCount, messages } = conversation

    this.userId = targetId
    this.unreadMessageCount = unreadMessageCount > 99 ? 99 : unreadMessageCount
    this.messages = messages
    this.userInfo = new UserInfo(targetId)
  }
}

class IM_Base {
  constructor(Vue) {
    this.bus = new Vue()
    this.IMEventType = IMEventType
    this.instance = null
    this.connected = false
    this.caller = null
    this.callSession = null

    // 初始化
    switch (process.env.MODE_ENV) {
      case 'dev':
        this.create('25wehl3u2vdlw')
        break
      case 'test':
        this.create('kj7swf8okmm72')
        break
      case 'pro':
        this.create('vnroth0kv2qko')
        break
      default:
        this.create('vnroth0kv2qko')
        break
    }
  }

  emit(data) {
    this.bus.$emit('IM_EVENT', data)
  }

  on(fn) {
    this.bus.$on('IM_EVENT', fn)
  }

  off(fn) {
    this.bus.$off('IM_EVENT', fn)
  }

  // 初始化融云IM对象
  create() {}

  // 销毁融云IM对象
  destroy() {}

  // 连接融云服务器
  connect() {}

  // 断开链接
  disconnect() {}

  // 初始化监听器
  initListener() {}

  // 获取指定会话
  getConversation() {}

  // 获取某个会话的历史消息记录
  getHistoryMessages() {}

  // 清除指定会话未读数
  clearUnreadCount() {}

  // 发送文本消息
  sendTextMessage() {}

  // 发送语音消息
  sendVoiceMessage() {}

  // 发起单人通话
  call() {}

  // 接听当前 callSession
  accept() {}

  // 挂断当前 callSession
  hungup() {}

  // 启用麦克风
  openMic() {}

  // 关闭麦克风
  closeMic() {}

  // 启用扬声器
  openSpeaker() {}

  // 关闭扬声器
  closeSpeaker() {}
}

export default {
  MessageType,
  ConversationType,
  IMEventType,
  Message_Base,
  Conversation_Base,
  Contact,
  IM_Base
}
